package com.otaku.admin.security;

import com.alibaba.fastjson.JSON;
import com.otaku.admin.util.ResultEnum;
import com.otaku.admin.util.ResultVO;
import com.otaku.admin.util.StringTypeConstant;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: zzx
 * @date: 2018/10/15 15:04
 * @description: 用户未登录时返回给前端的数据
 */
@Component
public class AjaxAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        /**
         * 1.携带新的token：当用户未进行注销操作，且数据库中refresh-token有效的前提下返回
         * 其他情况提示用户未登陆
         */
        String attribute = (String) httpServletRequest.getAttribute(StringTypeConstant.REFRESH_TOKEN_REQUEST);
        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        if (StringUtils.isEmpty(attribute)){
            httpServletResponse.getWriter().write(JSON.toJSONString(ResultVO.result(ResultEnum.USER_NEED_AUTHORITIES, false)));
        } else {
            httpServletRequest.removeAttribute(StringTypeConstant.REFRESH_TOKEN_REQUEST);
            httpServletResponse.getWriter().write(JSON.toJSONString(ResultVO.result(ResultEnum.REFRESH_TOKEN, attribute, true)));
        }
    }

}
